$(function() {
    var rows_delete = 0;
    var mode = "add";
    var m_id = 0;
    var url = 'controls/stock_model.php';
    var pid = 0;
	var pcode='';
    var eid=0;
	
	
	if (_dd==1){
		$("#btnAdd").show();
	}else{
		$("#btnAdd").hide();
	}
	
    LoadData('', '', _cdate, _cdate, '');

	
	$.get(url, {"m": "employee"}, function(data) {
        var obj = eval('(' + data + ')');
        if (obj != null) {
            $.each(obj, function(index, text) {
                $("#cboEmployeeName").append(
                        $('<option></option>').val(text).html(index)
                        );
            });
		 
        }
    });
	
   	var checkDate = $('.btndate1').datepicker().on('changeDate', function(ev) {
	  checkDate.hide();
	}).data('datepicker');
	
	var checkDate2 = $('.btndate2').datepicker().on('changeDate', function(ev) {
	  checkDate2.hide();
	}).data('datepicker');
	
	$("#txtDateFrom_s,#txtDateTo_s").val(_cdate);
	
    $("#txtAmount").keypress(function(e) {

        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });


    function checkControl() {
        var bln = true;
        //if ($("#txtProduct").val() == "" || pid == "" || pid == 0) {
        //    $("#txtProduct").attr('style', "background-color:#fddedb;border:1px solid #f99891");
        //    bln = bln && false;
       // } else {
       //     $("#txtProduct").removeAttr('style');
       //     bln = bln && true;
       // }
        if ($("#txtAmount").val() == "") {
            $("#txtAmount").attr('style', "background-color:#fddedb;border:1px solid #f99891");
            bln = bln && true;
        } else {
            $("#txtAmount").removeAttr('style');
            bln = bln && true;
        }
        return bln;
    }
   
    function checkStock(){
             $.ajax({
                type: 'POST',
                cache: false,
                url: url,
                data: {"m": "checkStock","pid":pid,   "amt": $("#txtAmount").val()},
                success: function(data) {
                    if (data=="1"){
                             $("#Error").css('display', 'none');
                        $("#table_detail").dataTable().fnAddData([
                           0, pid,pcode ,  $("#cboProduct option:selected").text(), $("#txtAmount").val()
                       ]);       
                    }else{
                         $("#Error").css('display', '');
                            $("#Error").html("ขอในสต๊อกไม่พอเบิก");
                    }
                }
            });
    }
    function checkDuplicate(){
        
            var rows = $('#table_detail').dataTable().fnGetNodes();

            for (var i = 0; i < rows.length; i++)
            {
                 var row_data = $('#table_detail').dataTable().fnGetData(rows[i]);
                if (row_data[1] == pid){
                    $("#Error").css('display', '');
                    $("#Error").html("มีรายการอยู่แล้ว");
                    return false;
                }
            }
             $("#Error").css('display', 'none'); 
             return true;
    }
    $("#btnAddProduct").live('click', function() {

        if (checkControl())
        {
			pid = $("#cboProduct").val();
			pcode = $("#cboProduct option:selected").attr('data-subtext');
            if (checkDuplicate())
             checkStock();
        }
		// $("#txtProduct").val("");
    });

    $("#btnSave").live('click', function() {
        $("#txtRequestDate").jqBootstrapValidation({preventSubmit: false,
            submitSuccess: function($form, event) {
                event.preventDefault();
            }
        });
		eid = $("#cboEmployeeName").val();
       /* if (eid==""){
             $("#txtEmployeeName").attr('style', "background-color:#fddedb;border:1px solid #f99891");
             return;
        }else{
            $("#txtEmployeeName").removeAttr('style');
        }
        */
         
        if (mode == "add") {
            var list = [];
            var rows = $('#table_detail').dataTable().fnGetNodes();

            for (var i = 0; i < rows.length; i++)
            {
                var row_data = $('#table_detail').dataTable().fnGetData(rows[i]);
                list.push({'pid': row_data[1],
                    'amt': row_data[4]});
            }

            var amt_total = rows.length;

            if (amt_total == 0) {
                $("#Error").css('display', '');
                $("#Error").html("กรุณาเลือกรายการ");
                return;
            } else {
                $("#Error").css('display', 'none');
            }
            var date = $("#txtRequestDate").val();
            var remark = $("#txtRemark").val();
            var ename = $("#cboEmployeeName option:selected").text();
             $("#popup").modal('hide');

            $.ajax({
                type: 'POST',
                cache: false,
                url: url,
                data: {"m": "add_shipment","date":date, "eid": eid, "amt": amt_total, "list": list, "remark": remark},
                success: function(data) {
                    var obj = eval('(' + data + ')');
                              
                    $("#resultData").dataTable().fnAddData([
                        0, obj['id'], date, ename  ,remark  , amt_total
                    ]);
                }
            });

        } else {

        }

        $("#txtRequestDate").jqBootstrapValidation("destroy");
    });
	
	$("#btnPrint").live('click',function(e	){
		e.preventDefault(); 
		 
       
		var form = $(this).closest('form');
		//alert($("input[name:pay]:checked").val());
		$("#frmshipment").get(0).setAttribute('action', 'rpt_shipment.php');
		$("#pid").val(m_id);
		 
		 form.attr('target', '_blank').submit().removeAttr('target').removeAttr('action');
	});
	
    $(".btnEdit").live('click', function() {
        $("#btnCancel").html('ปิด');
        mode = "edit";
		
		$(".print_control").show();
        $(".hidden_control").hide();
        var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
        var data = $('#resultData').dataTable().fnGetData(rows);

        m_id = data[1];
        SetTableDetail(m_id);

        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "getShipmentDetail", "id": m_id},
            success: function(data) {
                
                var obj = eval('(' + data + ')');
			 
                $("#cboEmployeeName").val(obj['name']);
                $("#txtRequestDate").val(obj['shipmentdate']);
                $("#txtRemark").val(obj['remark']);
            }
        });
    });
    $("#btnAdd").live('click', function() {
        $("#btnCancel").html('ยกเลิก');
        $("#Error").css('display', 'none');
       
        $("#txtRequestDate , #txtRemark").val('');

        mode = "add";
		$(".print_control").hide();
        $(".hidden_control").show();
        var now = new Date();
        var today = ("0" + now.getDate()).slice(-2) + '/' + ("0" + (now.getMonth() + 1)).slice(-2) + '/' + now.getFullYear();
        $("#txtRequestDate").val(today);
         
        //First Time 
        SetTableDetail(0);

    });
    $(".btnDel_detail").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#table_detail').dataTable().fnGetPosition(rows);
        $('#table_detail').dataTable().fnDeleteRow(rows_delete);
        $('#table_detail').dataTable().fnDraw();
    });
    $("#btnSearch").click(function() {

        var _code = $("#txtCode").val();
        var _pname = $("#txtProductName").val();
        var _df = $("#txtDateFrom_s").val();
        var _dt = $("#txtDateTo_s").val();
        var _emp = $("#txtEmpName").val();
         

        LoadData(_code, _pname, _df, _dt, _emp);
    });

    
    //Main Table
    function LoadData(code, pname , df, dt, name) {
	
		BlockUI();
        $("#resultData tbody tr").remove();


        $('#resultData').dataTable({
            "bProcessing": true,
            "bFilter": false,
            "bLengthChange": false,
			"bAutoWidth": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_shipment"},
                {"name": "code", "value": code},
                {"name": "pname", "value": pname},
                {"name": "datefrom", "value": df},
                {"name": "dateto", "value": dt},
                {"name": "ename", "value": name}

                );
            },
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1]},
                {"bSortable": true, "aTargets": [2], "sClass": "center"},
                {"bSortable": true, "aTargets": [3], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [4], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [5], "sClass": "text-right"},
                {"aTargets": [6],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						if (_it==1)
                        return "<a href='#popup' data-toggle='modal'><img src='img/List.png' class='btnEdit' style='cursor:pointer;'/></a>";
						else
						return "";
                    }
                },
                {"aTargets": [7],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						if (_te==1)
                            return "<a href='#popupConfirm' data-toggle='modal'><img src='img/delete-file.png' class='btnDel' style='cursor:pointer;'/></a>";
						else
							return "";
                    }
                }

            ]
            , "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = oSettings.aiDisplay.length; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
				
                }
				
					 $.unblockUI();

            }
        });

    }

 
	
    $("#btnDelete").live('click', function() {

        var row_id = $('#resultData').dataTable().fnGetData(rows_delete);

        var id = row_id[1];

        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "del_shipment", "id": id},
            success: function(data) {
                $("#popupConfirm").modal('hide');

                $('#resultData').dataTable().fnDeleteRow(rows_delete);
                $('#resultData').dataTable().fnDraw();
            }
        });

    });

    $(".btnDel").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#resultData').dataTable().fnGetPosition(rows);

    });

   $.post(url, {"m": "getProductShipment"}, function(data) {
			
			var obj = eval('(' + data + ')');
			if (obj != null) {
				$("#cboProduct").find('option').remove();	
				$.each(obj, function(index, text) {
					$("#cboProduct").append(
							$('<option data-subtext="'+text['code']+'"></option>').val(index).html(text['name'])
					);
				});
				$(".select_product").selectpicker('refresh');
			 
			}
	});
    function LoadProductToTextBox(t) {
        //Clear data
        $('#txtProduct').off();
        $('#txtProduct').data('typeahead', (data = null));

        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "getProductShipment"},
            success: function(data) {
                var sourceArr = [];
                var jsonObj = $.parseJSON(data);

                $('#txtProduct').typeahead({
                    source: function(query, process) {
                        objects = [];
                        map = {};
                        var data = jsonObj; // Or get your JSON dynamically and load it into this variable
                        $.each(data, function(i, object) {
                            map[object.label] = object;
                            objects.push(object.label);
                        });
                        process(objects);
                    },
                    updater: function(item) {
                        // $('hiddenInputElement').val(map[item].id);
                        pid = map[item].id;
						pcode= map[item].code;
                        return item;
                    }
                });
            }
        });
    }
    function LoadCustomerToTextBox(t) {
        //Clear data
        $('#txtEmployeeName').off();
        $('#txtEmployeeName').data('typeahead', (data = null));

        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "getCustomer"},
            success: function(data) {
                var sourceArr = [];
                var jsonObj = $.parseJSON(data);

                $('#txtEmployeeName').typeahead({
                    source: function(query, process) {
                        objects = [];
                        map = {};
                        var data = jsonObj; // Or get your JSON dynamically and load it into this variable
                        $.each(data, function(i, object) {
                            map[object.label] = object;
                            objects.push(object.label);
                        });
                        process(objects);
                    },
                    updater: function(item) {
                        // $('hiddenInputElement').val(map[item].id);
                        eid = map[item].id;
                        return item;
                    }
                });
            }
        });
    }
    //initial get product 
    //if ($("#txtProduct")[0]) {
   //     LoadProductToTextBox(2);
   // } 
  // if ($("#txtEmployeeName")[0]){
      // LoadCustomerToTextBox();
   //}
    function SetTableDetail(id) {
        $("#table_detail").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
            "bPaginate": false,
            "bLengthChange": false,
			"bAutoWidth": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "prd_detail"},
                {"name": "id", "value": id},
                {"name": "type", "value": "SM"}
                );
            },
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1]},
				{"bSortable": true, "aTargets": [2], "sClass": "text-center"},
                {"bSortable": true, "aTargets": [3], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [4], "sClass": "text-right"},
                {"aTargets": [5],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                        if (mode == "add")
                            return "<a href='#'  ><img src='img/delete-file.png' class='btnDel_detail' style='cursor:pointer;'/></a>";
                        else
                            return "";
                    }
                }

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });

    }
});


